import * as qs from "qs";

const postHeader = {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'};
const getHeader = {'Content-Type': 'application/json;charset=utf-8'};

export function ajaxFetch(url, data, method) {
	if (method === 'get') {
		return getFetch(url, data, getHeader);
	} else {
		return postFetch(url, data, postHeader)
	}
}

//post请求
function postFetch(url, data, header) {
	return fetch(url, {
		method: 'post',
		headers: header,
		body: qs.stringify(data),
	}).then(res => {
		return res.json()
	})
}

//get请求（请求的参数直接拼接在url上面）
function getFetch(url, data, header) {
	let data_url = ''; //拼接的url
	let keys = Object.keys(data); //获取传参的键
	//拼接传参
	for (let i = 0; i < keys.length; i++) {
		data_url += `${keys[i]} = ${data[keys[i]]}&`
	}
	return fetch(`${url}?${data_url}`, {
		method: 'get',
		headers: header,
	}).then(res => {
		return res.json()
	})
}
